/*
 * ------------------------------------------------------------------
 * Copyright © 2017 Hangzhou DtDream Technology Co.,Lt d. All rights reserved.
 * ------------------------------------------------------------------
 *       Product:
 *   Module Name:
 *  Date Created: 2023/7/12
 *   Description:
 * ------------------------------------------------------------------
 * Modification History
 * DATE            Name           Description
 * ------------------------------------------------------------------
 * 2023/7/12    小谷 g2038          created
 * ------------------------------------------------------------------
 */
package com.gujh.security.config;

import com.gujh.security.authentication.SecurityAuthenticationHandler;
import com.gujh.security.authentication.jwt.JwtAuthenticationConfigurer;
import com.gujh.security.authentication.jwt.JwtAuthenticationSuccessHandler;
import com.gujh.security.authentication.sms.SmsAuthenticationConfigurer;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@AllArgsConstructor
public class SpringSecurityConfig {

    private SecurityAuthenticationHandler securityAuthenticationHandler;

    private JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandler;

    private JwtAuthenticationConfigurer jwtAuthenticationConfigurer;

    private SmsAuthenticationConfigurer smsAuthenticationConfigurer;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .securityMatcher("/**")
                .authorizeHttpRequests(request -> request
                        .requestMatchers("/login**", "/logout").permitAll()
                        .requestMatchers("*.css", "*.js").permitAll()
                        .requestMatchers("/sms/send/Captcha").permitAll()
                        .anyRequest().authenticated())
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(securityAuthenticationHandler)
                        .accessDeniedHandler(securityAuthenticationHandler))
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .logoutSuccessHandler(securityAuthenticationHandler)
                        .clearAuthentication(true))
                .csrf(AbstractHttpConfigurer::disable);

        http.apply(smsAuthenticationConfigurer)
                .authenticationSuccessHandler(jwtAuthenticationSuccessHandler)
                .authenticationFailureHandler(securityAuthenticationHandler);

        http.apply(jwtAuthenticationConfigurer);
        return http.build();
    }
}
